use anyhow::{Context, Result};
use eframe::egui;
use regex::Regex;
use reqwest::Client;
use serde_json::json;
use std::io::{stdin, BufRead};

// 调用 DashScope API 生成对联
async fn generate_couplet_by_dashscope(
    keyword: &str,
    api_key: &str,
) -> Result<(String, String, String)> {
    let client = Client::new();
    let api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    let prompt = format!(
        "请根据关键字“{}”生成一副对联，输出格式为：上联|下联|横幅",
        keyword
    );
    let body = json!({
        "model": "qwen-7b-chat",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ]
        },
        "parameters": {
            "top_p": 0.8,
            "temperature": 0.8
        }
    });

    let response = client
        .post(api_url)
        .header("Authorization", format!("Bearer {}", api_key))
        .json(&body)
        .send()
        .await
        .context("Failed to send request")?;

    let response_json = response
        .json::<serde_json::Value>()
        .await
        .context("Failed to parse response as JSON")?;
    println!("API 返回的 JSON 结果：{:?}", response_json);
    let result = response_json["output"]["text"].as_str().unwrap_or("");
    println!("API 返回的文本结果：{}", result);

    // 使用正则表达式匹配完整格式
    /*修改说明：
    正则表达式添加(?m)多行模式和^$行首尾锚定，确保匹配完整行内容
    增加\s*处理可能存在的空格
    新增专门处理分行格式的正则表达式re_multi_line
    */
    // 优化后的正则表达式（处理带换行符的情况）
    let re = Regex::new(
        r"(?m)^上联[：:]?\s*(.*?)[，,]\s*下联[：:]?\s*(.*?)[，,。]\s*横幅[：:]?\s*(.*)$",
    )
    .unwrap();
    //let re = Regex::new(r"(?m)^上联[：:]?\s*([^，下联]+)(?:[，,]\s*下联[：:]?\s*([^，横幅]+)[，,]\s*横幅[：:]?\s*(.+))?").unwrap();

    if let Some(caps) = re.captures(result) {
        let upper = caps[1].trim().to_string();
        let lower = caps[2].trim().to_string();
        let banner = caps[3].trim().to_string();
        return Ok((upper, lower, banner));
    }

    // 新增对无分隔符情况的处理
    //let re_multi_line = Regex::new(r"(?m)^上联[：:]?\s*(.+?)\s*$\n^下联[：:]?\s*(.+?)\s*$\n^横幅[：:]?\s*(.+?)\s*$").unwrap();
    let re_multi_line =
        Regex::new(r"(?m)^上联[：:]?\s*([^\n]+)\n下联[：:]?\s*([^\n]+)\n横幅[：:]?\s*([^\n]+)$")
            .unwrap();

    if let Some(caps) = re_multi_line.captures(result) {
        /*let upper = caps[1].into().trim_matches(|c| c == '，' || c == ',').to_string();
        let lower = caps[2].trim().trim_matches(|c| c == '，' || c == ',').to_string();
        let banner = caps[3].trim().trim_matches(|c| c == '。' || c == '.').to_string();
        return Ok((upper, lower, banner));*/
        return Ok((caps[1].into(), caps[2].into(), caps[3].into()));
    }

    let mut parts: Vec<&str> = result.split('\n').collect();

    // 先尝试按换行符分割
    if parts.len() < 2 {
        // 如果按换行符分割失败，则尝试按标点分割
        parts = result.split([',', '。']).collect();
    }
    if parts.len() >= 2 {
        let upper = parts[0].trim_start_matches("上联:").to_string();
        let lower = parts[1].trim_start_matches("下联:").to_string();
        //let banner = parts[2].trim_start_matches("横幅:").to_string();
        // 尝试获取横幅，如果没有则使用默认横幅
        let banner = if parts.len() > 2 {
            parts[2].trim_start_matches("横幅:").to_string()
        } else {
            "吉祥如意".to_string()
        };
        Ok((upper, lower, banner))

        //Ok((parts[0].to_string(), parts[1].to_string(), parts[2].to_string()))
    } else {
        Err(anyhow::anyhow!("Invalid response format: {}", result))
    }
}

// 原有的生成对联函数，保留作为备用
fn generate_couplet(keyword: &str) -> (String, String, String) {
    let upper = format!("{}添喜福满门", keyword);
    let lower = format!("{}贺春财盈户", keyword);
    let banner = "吉祥如意";
    (upper, lower, banner.to_string())
}

#[tokio::main]
pub async fn main_demo() {
    let api_key = "sk-36833aab956745f99ca30f54ab246e43"; // 替换为你的 DashScope API Key
    println!("请输入关键字:");
    let mut input = String::new();
    stdin().lock().read_line(&mut input).expect("读取输入失败");
    let keyword = input.trim();

    match generate_couplet_by_dashscope(keyword, api_key).await {
        Ok((upper, lower, banner)) => {
            println!("上联: {}", upper);
            println!("下联: {}", lower);
            println!("横幅: {}", banner);
        }
        Err(e) => {
            // 如果调用 DashScope API 失败，使用本地简单生成逻辑
            eprintln!("API 请求失败: {}", e);
            let (upper, lower, banner) = generate_couplet(keyword);
            println!("上联: {}", upper);
            println!("下联: {}", lower);
            println!("横幅: {}", banner);
        }
    }
}

// ... 保留原有生成函数 ...

#[derive(Default)]
pub struct CoupletApp {
    input: String,
    result: Option<(String, String, String)>,
    error: Option<String>,
    // 新增异步任务状态
    task: Option<tokio::task::JoinHandle<Result<(String, String, String), anyhow::Error>>>,
}

impl eframe::App for CoupletApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // 修正后的字体配置（应放在应用初始化处）
        ctx.set_fonts(eframe::egui::FontDefinitions {
            font_data: {
                let mut map = std::collections::BTreeMap::new();
                map.insert(
                    "NotoSansCJK".to_string(),
                    eframe::egui::FontData::from_static(include_bytes!(
                        "../fonts/NotoSansCJKsc-Regular.otf"
                    ))
                    .into(),
                );
                map
            },
            families: vec![
                (
                    eframe::egui::FontFamily::Proportional,
                    vec!["NotoSansCJK".to_string()],
                ),
                (
                    eframe::egui::FontFamily::Monospace,
                    vec!["NotoSansCJK".to_string()],
                ),
            ]
            .into_iter()
            .collect(),
        });
        let api_key = "sk-36833aab956745f99ca30f54ab246e43"; // 替换为你的 DashScope API Key
                                                             // 检查异步任务是否完成
        if let Some(task) = &mut self.task {
            if task.is_finished() {
                let result = futures::executor::block_on(task);
                match result {
                    Ok(Ok((upper, lower, banner))) => {
                        self.result = Some((upper, lower, banner));
                        self.error = None;
                    }
                    _ => {
                        self.result = Some(generate_couplet(&self.input));
                        self.error = None;
                    }
                }
                self.task = None;
            }
        }
        // 界面布局
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.vertical(|ui| {
                // 输入框和按钮
                ui.horizontal(|ui| {
                    ui.label("关键字：");
                    ui.text_edit_singleline(&mut self.input);
                    if ui.button("生成对联").clicked() && self.task.is_none() {
                        if self.input.is_empty() {
                            self.error = Some("请输入关键字".into());
                        } else {
                            let keyword = self.input.clone();
                            let api_key = api_key.to_string();
                            self.task = Some(tokio::runtime::Handle::current().spawn(async move {
                                generate_couplet_by_dashscope(&keyword, &api_key).await
                            }));
                        }
                    }
                });

                // 结果显示区域
                if let Some((upper, lower, banner)) = &self.result {
                    ui.separator();
                    ui.heading("生成结果");
                    /*ui.label(format!("上联：{}", upper)); //移除"上联:"前缀
                    ui.label(format!("下联：{}", lower)); //移除"下联:"前缀
                    ui.label(format!("横幅: {}", banner));*/
                    // 横幅居中显示
                    ui.horizontal(|ui| {
                        ui.add_space(ui.available_width() / 2.5);
                        ui.label(
                            egui::RichText::new(banner)
                                .size(24.0)
                                .color(egui::Color32::GOLD),
                        );
                    });

                    /*  // 对联垂直布局
                        ui.columns(2, |columns| {
                            // 上联（右列）
                            columns[1].vertical(|ui| {
                                ui.add_space(20.0);
                                for c in upper.chars() {
                                    ui.label(egui::RichText::new(c.to_string())
                                        .size(30.0)
                                        .color(egui::Color32::RED));
                                }
                            });
                            // 下联（左列）
                            columns[0].vertical(|ui| {
                                ui.add_space(20.0);
                                for c in lower.chars() {
                                    ui.label(egui::RichText::new(c.to_string())
                                        .size(30.0)
                                        .color(egui::Color32::RED));
                                }
                            });
                    });*/
                    // 上下联布局
                    ui.horizontal(|ui| {
                        // 下联左侧1/4处
                        //ui.add_space(ui.available_width()/4.0 - 40.0); // 调整间距
                        ui.add_space(ui.available_width() / 4.0); // 调整间距
                        ui.vertical(|ui| {
                            for c in lower.chars() {
                                ui.label(
                                    egui::RichText::new(c.to_string())
                                        .size(30.0)
                                        .color(egui::Color32::GOLD),
                                );
                            }
                        });

                        ui.add_space(ui.available_width() / 4.0); // 调整间距
                                                                  // 使用自定义绘制实现倒转福字
                                                                  //ui.vertical_centered(|ui| {
                                                                  // 添加倒置的幅字
                        ui.vertical(|ui| {
                            ui.label(
                                egui::RichText::new("幅")
                                    .color(egui::Color32::GOLD)
                                    .size(100.0)
                                    .heading()
                                    .underline() // 添加下划线模拟倒置效果
                                    .italics(), // 斜体增强视觉效果
                            );
                        });

                        // 上联右侧1/4处
                        //ui.add_space(ui.available_width() / 2.0); // 中间留空
                        ui.add_space(ui.available_width() / 4.0); // 调整间距
                        ui.vertical(|ui| {
                            for c in upper.chars() {
                                ui.label(
                                    egui::RichText::new(c.to_string())
                                        .size(30.0)
                                        .color(egui::Color32::GOLD),
                                );
                            }
                        });
                    });
                };
            });

            // 错误提示
            if let Some(err) = &self.error {
                ui.colored_label(egui::Color32::RED, err);
            }
        }); // 修复vertical布局结束括号
    } // 修复CentralPanel布局结束括号
}

// 修改主函数

/*use std::io::{stdin, BufRead};
use reqwest::Client;
use serde_json::json;
use anyhow::{Context, Result};

// 调用 DashScope API 生成对联
async fn generate_couplet_by_dashscope(keyword: &str, api_key: &str) -> Result<(String, String, String), reqwest::Error> {
    let client = Client::new();
    let api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    let prompt = format!("请根据关键字“{}”生成一副对联，输出格式为：上联|下联|横幅", keyword);
    let body = json!({
        "model": "qwen-7b-chat",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ]
        },
        "parameters": {
            "top_p": 0.8,
            "temperature": 0.8
        }
    });

    let response = client.post(api_url)
       .header("Authorization", format!("Bearer {}", api_key))
       .json(&body)
       .send()
       .await?;

    let response_json = response.json::<serde_json::Value>().await?;
    let result = response_json["output"]["text"].as_str().unwrap_or("");
    let parts: Vec<&str> = result.split('|').collect();
    if parts.len() == 3 {
        Ok((parts[0].to_string(), parts[1].to_string(), parts[2].to_string()))
    } else {
        Err(reqwest::Error::new(reqwest::StatusCode::INTERNAL_SERVER_ERROR, "Invalid response format"))
    }
}

// 原有的生成对联函数，保留作为备用
fn generate_couplet(keyword: &str) -> (String, String, String) {
    let upper = format!("{}添喜福满门", keyword);
    let lower = format!("{}贺春财盈户", keyword);
    let banner = "吉祥如意";
    (upper, lower, banner.to_string())
}

#[tokio::main]
pub async fn main_demo() {
    let api_key = "sk-36833aab956745f99ca30f54ab246e43"; // 替换为你的 DashScope API Key
    println!("请输入关键字:");
    let mut input = String::new();
    stdin().lock().read_line(&mut input).expect("读取输入失败");
    let keyword = input.trim();

    match generate_couplet_by_dashscope(keyword, api_key).await {
        Ok((upper, lower, banner)) => {
            println!("上联: {}", upper);
            println!("下联: {}", lower);
            println!("横幅: {}", banner);
        }
        Err(_) => {
            // 如果调用 DashScope API 失败，使用本地简单生成逻辑
            let (upper, lower, banner) = generate_couplet(keyword);
            println!("上联: {}", upper);
            println!("下联: {}", lower);
            println!("横幅: {}", banner);
        }
    }
}
*/

/*
fn generate_couplet(keyword: &str) -> (String, String, String) {
    // 这里只是简单示例，根据关键字生成对联
    let upper = format!("{}添喜福满门", keyword);
    let lower = format!("{}贺春财盈户", keyword);
    let banner = "吉祥如意";

    (upper, lower, banner.to_string())
}

pub  fn main_demo() {
    println!("请输入关键字:");
    let mut input = String::new();
    stdin().lock().read_line(&mut input).expect("读取输入失败");
    let keyword = input.trim();

    let (upper, lower, banner) = generate_couplet(keyword);
    println!("上联: {}", upper);
    println!("下联: {}", lower);
    println!("横幅: {}", banner);
}
*/
